<template>
  <div>
    <div class="id">
      <div @click="popupShow" class="left">
        <van-icon class="icon" size="22" name="wap-nav" />
        <img class="leftimg" src="@/assets/tab/logo.png" alt />
      </div>
      <div class="right">
        <div class="wangluo" @click="wlPopShow">
          <img v-if="store.state.user.chainId === '0x1'" src="@/assets/home/eth.png" alt="">
          <img v-if="store.state.user.chainId === '0x38'" src="@/assets/home/bnb.png" alt="">
          <img v-if="store.state.user.chainId === '0xa4b1'" src="@/assets/home/arb.png" alt="">
          <img v-if="store.state.user.chainId === '0x144'" src="@/assets/home/zk.png" alt="">
        </div>
        <div @click="goto('/mine')" v-if="truncatedAccount" class="user">
          <img src="@/assets/home/user.png" class="userimg" alt="">
          <span class="username">{{ truncatedAccount }}</span>
        </div>
        <div v-else @click="connect" class="btn">{{ $t("連接") }}</div>
        <img @click="bottmepopupShow" class="rightimg" src="@/assets/tab/lang.png" />
      </div>
    </div>
    <van-popup class="leftPop" v-model:show="leftshow" position="left"
      style="height: 100%; width: 60%; background-color: #2e323b">
      <img class="img" src="@/assets/tab/logotext.png" alt />
      <div class="list">
        <div class="item" @click="goto('/page/home')">
          <img class="itemimg" src="@/assets/tab/home.png" alt />
          <span class="itemText">{{ $t("首頁") }}</span>
        </div>
        <div class="item" @click="goto('/page/chat')">
          <img class="itemimg" src="@/assets/tab/dash.png" alt />
          <span class="itemText">{{ $t("儀表板") }}</span>
        </div>
        <div @click="goto('/page/trade')" class="item">
          <img class="itemimg" src="@/assets/tab/trade.png" alt />
          <span class="itemText">{{ $t("交易") }}</span>
        </div>
        <div @click="goto('/node')" class="item">
          <img class="itemimg" src="@/assets/tab/node.png" alt />
          <span class="itemText">{{ $t("節點") }}</span>
        </div>
        <div class="item" @click="goto('/launchpad')">
          <img class="itemimg" src="@/assets/tab/lauch.png" alt />
          <span class="itemText">{{ $t("啓動臺") }}</span>
        </div>
        <div class="item" @click="goto('/page/pools')">
          <img class="itemimg" src="@/assets/home/pools.png" alt />
          <span class="itemText">Pools</span>
        </div>
        <div @click="goto('/page/trading')" class="item">
          <img class="itemimg" src="@/assets/tab/market.png" alt />
          <span class="itemText">{{ $t("市場") }}</span>
        </div>
        <div @click="goto('/page/account')" class="item">
          <img class="itemimg" src="@/assets/tab/account.png" alt />
          <span class="itemText">Tokens</span>
        </div>
        <div @click="goto('/invitation')" class="item">
          <img class="itemimg" src="@/assets/tab/invitation.png" alt />
          <span class="itemText">{{ $t("鏈條") }}</span>
        </div>
        <div @click="goto('/mine')" class="item">
          <img class="itemimg" src="@/assets/tab/mine.png" alt />
          <span class="itemText">{{ $t("設置") }}</span>
        </div>
      </div>
    </van-popup>
    <van-popup class="btmPopup" v-model:show="bottomshow" position="bottom" style>
      <div class="btmPop">
        <div class="btndiv">
          <span :style="{ color: i18n.global.locale == 'en' ? '#a8aeae' : '#fff' }" @click="setLang('zh')">中文繁体</span>
          <span :style="{ color: i18n.global.locale == 'zh' ? '#a8aeae' : '#fff' }" @click="setLang('en')">English</span>
        </div>
      </div>
    </van-popup>
    <van-popup class="btmPopup" v-model:show="bottomshow2" position="bottom" style>
      <div class="btmPop">
        <div class="btndiv">
          <span @click="setwallet(0)">小狐狸钱包</span>
          <span @click="setwallet(1)">TP钱包</span>
        </div>
      </div>
    </van-popup>
    <van-popup class="wlPopup" v-model:show="wlPop" :round="true" position="bottom" style>
      <div class="btmPop">
        <div @click="changelian('0x1')" class="btndiv">
          <div class="le">
            <img src="@/assets/home/eth.png" alt="">
            <span>Ethereum</span>
          </div>
          <div v-show="store.state.user.chainId === '0x1'" class="ri"></div>
        </div>
        <div @click="changelian('0x38')" class="btndiv">
          <div class="le">
            <img src="@/assets/home/bnb.png" alt="">
            <span>BNB Smart Chain</span>
          </div>
          <div v-show="store.state.user.chainId === '0x38'" class="ri"></div>
        </div>
        <div @click="changelian('0xa4b1')" class="btndiv">
          <div class="le">
            <img src="@/assets/home/arb.png" alt="">
            <span>Arbitrum One</span>
          </div>
          <div v-show="store.state.user.chainId === '0xa4b1'" class="ri"></div>
        </div>
        <div @click="changelian('0x144')" class="btndiv">
          <div class="le">
            <img src="@/assets/home/zk.png" alt="">
            <span>zkSync</span>
          </div>
          <div v-show="store.state.user.chainId === '0x144'" class="ri"></div>
        </div>
      </div>
    </van-popup>
    <router-view />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import i18n from "@/locales/i18n";
import store from "@/store/index";

const router = useRouter();

// web3--------------------------------------------------------------------

import Web3 from 'web3';

async function MetaMask() {
  if (window.ethereum) {
    try {
      const web3 = new Web3(window.ethereum);
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      const selectedAccount = accounts[0];
      const balanceWei = await web3.eth.getBalance(selectedAccount);
      console.log(balanceWei);
      const balance = web3.utils.fromWei(balanceWei, 'ether');
      console.log();
      //获取网络id 十进制
      const networkId = await web3.eth.net.getId();
      console.log(networkId);
      //获取网络id 十六进制
      const chainId = await window.ethereum.request({ method: 'eth_chainId' });
      console.log(chainId);
      window.ethereum.on('chainChanged', handleChainChanged);
      store.commit("setUser", {
        isConnected: true,
        account: selectedAccount,
        balance,
        chainId,
      })
      console.log({
        isConnected: true,
        account: selectedAccount,
        balance,
        chainId
      });
    } catch (error) {
      console.log(error);
      alert(error.message);
    }
  } else {
    alert('请安装MetaMask插件');
  }
};

function handleChainChanged(chainId) {
  // We recommend reloading the page, unless you must do otherwise.
  // window.location.reload();
  console.log(chainId);
  console.log('网络切换了');
  changelian(chainId)
}

//网络切换
async function changelian(val) {
  try {
    await window.ethereum.request({
      method: 'wallet_switchEthereumChain',
      params: [
        {
          chainId: val
        },
      ],
    });
    // 在这里执行成功后的代码
    store.commit('setWL', val);
    wlPop.value = false;
  } catch (error) {
    // 处理请求失败的情况
    console.error('切换 Ethereum 链失败', error);
  }


  // window.ethereum.request({
  //   method: 'wallet_addEthereumChain',
  //   params: [{
  //     chainId: '0x38',
  //     chainName: 'Binance Smart Chain Mainnet',
  //     nativeCurrency: {
  //       name: 'BNB',
  //       symbol: 'bnb',
  //       decimals: 18,
  //     },
  //     rpcUrls: ['https://bsc-dataseed.binance.org/'],
  //     blockExplorerUrls: ['https://bscscan.com/'],
  //   }],
  // }).then(() => {
  //   console.log('success');
  // }).catch((error) => {
  //   console.log(error);
  // });
}

async function TP() {
  if (window.ethereum) {
    try {
      const web3 = new Web3(window.ethereum)
      const selectedAccount = await window.ethereum.request({ method: "eth_requestAccounts" })
        .then((accounts) => accounts[0])
        .catch(() => { throw Error("No account selected") })
      const balance = await web3.eth.getBalance(selectedAccount)
        .then((balance) => web3.utils.fromWei(balance, "ether"))
      store.commit("setUser", {
        isConnected: true,
        account: selectedAccount,
        balance,
      })
    } catch (error) {
      alert(error)
    }
  } else {
    alert("Wallet not found")
  }
}

// web3--------------------------------------------------------------------

const truncatedAccount = computed(() => {
  if (!store.state.user.account) return
  const account = store.state.user.account;
  if (account.length <= 7) {
    return account;
  } else {
    const frontPart = account.slice(0, 4);
    const backPart = account.slice(-4);
    return frontPart + '...' + backPart;
  }
});

const leftshow = ref(false);
const bottomshow = ref(false);
const bottomshow2 = ref(false);
const wlPop = ref(false);

function popupShow() {
  leftshow.value = true;
}

function bottmepopupShow() {
  bottomshow.value = true;
}

function wlPopShow() {
  wlPop.value = true;
}

function goto(url) {
  router.push(url);
  leftshow.value = false;
}

function setLang(val) {
  localStorage.setItem("lang", val);
  i18n.global.locale = val;
  bottomshow.value = false;
}

function connect() {
  MetaMask()
  // bottomshow2.value = true
}

function setwallet(val) {
  console.log(val);
  if (val === 0) {
    MetaMask()
  } else {
    TP()
  }
  bottomshow2.value = false
}
</script>

<style lang="scss">
body {
  margin: 0;
}

.id {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 44px;
  background-color: #2e323b;
  box-sizing: border-box;
  padding: 0 10px;

  .left {
    display: flex;
    // justify-content: center;
    align-items: center;
    height: 44px;

    .icon {
      color: #fff;
    }

    .leftimg {
      width: 26px;
      height: 26px;
      margin-left: 10px;
    }
  }

  .right {
    display: flex;
    // justify-content: center;
    align-items: center;
    height: 44px;

    .wangluo {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 43px;
      height: 30px;
      border: 1px solid #f2ce3d;
      border-radius: 1000px;
      margin-right: 10px;

      img {
        width: 20px;
        height: 20px;
      }

    }

    .user {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 110px;
      height: 30px;
      background-color: #f2ce3d;
      border-radius: 100px;
      padding: 5px 12px;
      box-sizing: border-box;

      .userimg {
        width: 20px;
        height: 20px;
      }

      .username {
        font-size: 13px;
        color: #000;
      }
    }

    .btn {
      font-size: 14px;
      text-align: center;
      line-height: 28px;
      width: 68px;
      height: 28px;
      border-radius: 14px;
      background-color: #f2ce3d;
    }

    .rightimg {
      width: 25px;
      height: 25px;
      margin-left: 10px;
    }
  }
}

.leftPop {
  padding: 20px;

  .img {
    width: 149px;
    height: 24px;
    margin-top: 24px;
    margin-bottom: 24px;
  }

  .list {
    .item {
      display: flex;
      // justify-content: center;
      align-items: center;
      padding: 12px 0;

      .itemimg {
        width: 24px;
        height: 24px;
      }

      .itemText {
        font-size: 14px;
        color: #fff;
        margin-left: 10px;
      }
    }
  }
}

.btmPopup {
  height: 126px;
  width: 100%;

  .btmPop {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: #2e323b;

    // border-radius: 10px 10px 0 0;
    .btndiv {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      width: 90%;
      height: 80%;
      border: 1px solid #313c3f;
      border-radius: 10px;
      font-size: 15px;

      span {
        font-size: 16px;
        color: #fff;
        margin-bottom: 10px;
      }
    }
  }
}



.wlPopup {
  height: 246px;
  width: 100%;

  .btmPop {
    display: flex;
    justify-content: center;
    flex-direction: column;
    width: 100%;
    height: 100%;
    padding: 15px;
    background-color: #2e323b;
    box-sizing: border-box;

    // border-radius: 10px 10px 0 0;
    .btndiv {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 7px 0;

      .le {
        display: flex;
        align-items: center;

        img {
          width: 32px;
          height: 32px;
        }

        span {
          font-size: 13px;
          color: #fff;
          margin-left: 10px;
        }
      }

      .ri {
        width: 14px;
        height: 14px;
        border-radius: 50%;
        background-color: rgb(46, 189, 133);
        margin-right: 5px;
      }

    }
  }
}
</style>
